package dfbz.com.dao;

import dfbz.com.dao.base.BaseDao;
import dfbz.com.model.User;
import dfbz.com.utils.JDBCUtil;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class UserDao extends BaseDao<User> {


    /**
     * 登录的sql（业务sql，不属于基本sql 增删改查，直接用BaseDao）
     *
     * @param username 用户名
     * @return User对象
     */
    public User findUserByName(String username) {

        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        //开启下划线->驼峰转换所用
        BasicRowProcessor processor = new BasicRowProcessor(new GenerousBeanProcessor());

        User user = null;
        try {
            user = qr.query("select * from user where username = ? limit 1", new BeanHandler<>(User.class,processor), username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }


    public Map<String, Object> findUserById(Integer userId) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        Map<String, Object> map = null;

        String sql = "select u.id,u.username,u.dept_id as deptId,d.`name` as deptName "+
                    "from user u "+
                    "left join dept d on u.dept_id =d.id "+
                    "where u.id = ? ";
        try {

            map = qr.query(sql, new MapHandler(), userId);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return map;
    }

    public User findUserByEmail(String email) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        //开启下划线->驼峰转换所用
        BasicRowProcessor processor = new BasicRowProcessor(new GenerousBeanProcessor());

        User user = null;

        try {
            user = qr.query("select * from user where email = ? LIMIT 1",new BeanHandler<>(User.class,processor),email);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
